package com.yuexunit.web.servlet;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yuexunit.finance.common.util.RandomUtil;
import com.yuexunit.finance.context.FinanceSessionContext;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.entity.EnterpriseGradeEvaluationEntity;
import com.yuexunit.finance.member.entity.lexicon.AuditStateEnum;
import com.yuexunit.finance.member.entity.lexicon.AuthenticationEnum;
import com.yuexunit.finance.member.service.EnterpriseGradeEvaluationService;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.finance.project.SettingConstants;
import com.yuexunit.finance.project.action.v1.FinanceSignatureActionApi;
import com.yuexunit.finance.project.entity.FinanceAuditLogEntity;
import com.yuexunit.finance.project.entity.lexicon.ApiFinanceStateEnum;
import com.yuexunit.finance.project.entity.lexicon.ApiTypeEnum;
import com.yuexunit.finance.project.service.FinanceAuditLogService;
import com.yuexunit.finance.system.action.v1.dto.SendLetterMessage;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.persist.annotation.Transactional;
import com.yuexunit.util.DateUtil;

import net.sf.json.JSONObject;

public class EQBNotifyServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Logger logger = LoggerFactory.getLogger(EQBNotifyServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	@Transactional
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//防止客户重复请求，完成就结束
		req.setCharacterEncoding("UTF-8");
		EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);
		FinanceAuditLogService financeAuditLogService = ComponentFactory.loadClass(FinanceAuditLogService.class);
		EnterpriseGradeEvaluationService enterpriseGradeEvaluationService = ComponentFactory.loadClass(EnterpriseGradeEvaluationService.class);
		FinanceSignatureActionApi financeSignatureActionApi = ComponentFactory.loadClass(FinanceSignatureActionApi.class);

		String requestInfo = req.getParameter("esign_return");
		String requestInfoD = URLDecoder.decode(requestInfo,"UTF-8");
		logger.info("requestInfo===========================" + requestInfo);
		logger.info("requestInfoD==========================" + requestInfoD);
		JSONObject info = JSONObject.fromObject(requestInfoD);
		String serviceId = info.get("serviceId").toString();
		String result = info.get("result").toString();
		String payedTime = info.get("payedTime").toString();
		String errorMessage = info.get("msg").toString();
		EnterpriseEntity entity = enterpriseService.inquireEnterpriseByServiceId(serviceId);
		
		if (entity == null || entity.getAuthentication() != AuthenticationEnum.PENDINGVERIFICATION) {
			return;
		}

		if ("SUCCESS".equals(result)) {
			entity.setAuthentication(AuthenticationEnum.PAID);
			entity.setPayedTime(payedTime);

			entity.setSubmitState(Boolean.TRUE);
			entity.setAuditState(AuditStateEnum.UNAUDIT);
			entity.setFinalState(ApiFinanceStateEnum.YW.getCode());
			entity.setAuditState1(Boolean.TRUE);
			entity.setAuditState2(Boolean.TRUE);
			entity.setAuditState3(Boolean.TRUE);
			entity.setAuditState4(Boolean.TRUE);
			entity.setAuditState5(Boolean.TRUE);
			entity.setAuditState6(Boolean.TRUE);
			entity.setAuditState7(Boolean.TRUE);
			entity.setAuditState8(Boolean.TRUE);
			entity.setAuditState9(Boolean.TRUE);
			entity.setAuditState10(Boolean.TRUE);
			entity.setAuditState11(Boolean.TRUE);
			entity.setAuditState12(Boolean.TRUE);
			entity.setAuditSubmitState1(Boolean.FALSE);
			entity.setAuditSubmitState2(Boolean.FALSE);
			entity.setAuditSubmitState3(Boolean.FALSE);
			entity.setAuditSubmitState4(Boolean.FALSE);
			entity.setAuditSubmitState5(Boolean.FALSE);
			entity.setAuditSubmitState6(Boolean.FALSE);
			entity.setAuditSubmitState7(Boolean.FALSE);
			entity.setAuditSubmitState8(Boolean.FALSE);
			entity.setAuditSubmitState9(Boolean.FALSE);
			entity.setAuditSubmitState10(Boolean.FALSE);
			entity.setAuditSubmitState11(Boolean.FALSE);
			entity.setAuditSubmitState12(Boolean.FALSE);
			entity.setCallback(Boolean.FALSE);
			entity.setAuditNumber(SettingConstants.PRE_AUDIT_NUMBER_ENTERPRISE + RandomUtil.generateTimeNumber());
			FinanceAuditLogEntity fale = new FinanceAuditLogEntity(DateUtil.now(), "客户", 1L, "客户" + entity.getEnterpriseName() + "发起客户认证申请", entity.getEnterpriseId(), Long.valueOf(ApiTypeEnum.QYYH.getCode()), FinanceSessionContext.getAccountId());
			financeAuditLogService.createFinanceAuditLogEntity(fale);
			enterpriseService.updateEnterprise(entity);
			EnterpriseGradeEvaluationEntity evaluation = new EnterpriseGradeEvaluationEntity();
			evaluation.setEnterpriseId(entity.getEnterpriseId());
			enterpriseGradeEvaluationService.createEnterpriseGradeEvaluation(evaluation);

			String tmp = "客户(%s)已提交资质认证，请及时审批！";
			SendLetterMessage.sendLetterMessage("clientManageDetailAudit1_1", String.format(tmp, entity.getEnterpriseName()));

			try {
				financeSignatureActionApi.addOrganize();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			// 打款失败
			entity.setAuthentication(AuthenticationEnum.ACFAILED);
		} 
		entity.setErrorMessage(errorMessage);
		enterpriseService.updateEnterprise(entity);

		logger.info(result);
		logger.info(payedTime);
		
		return;
	}
}
